#This code is licensed under the MIT License
#Note: Currently doesn't work great if a link contains multiple types of tracking
import discord
import logging
import re
from urllib.parse import urlparse

#You will likely want to change the logging level
logging.basicConfig(level=logging.INFO)

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    #Ignores messages from the bot
    if message.author == client.user:
        return

    #if message.content.startswith('$hello'):
        #await message.channel.send('Hello!')

    #detects URLs within the message
    found_urls = re.findall("(?:(?:https?|ftp):\/\/)?[\w/\-?=%.&]+\.[\w/\-?=%.&]+", message.content)
    if found_urls:
        for url in found_urls:
            #initialises the variable that enables message sending
            utm_detected = False
            #uses urllib.parse.urlparse() to convert the URL into a list of components
            parsed_url = urlparse(url)
            #splits the queries into a list to be processed individually
            queries_list = parsed_url.query.split("&")
            #this is a list for the queries that aren't tracking
            new_query = []

            #iterate through each query and see if it matches a tracker definition, if it does it enables the messaging variable and sets the tracking type string
            #If the query doesn't match it's added to new_query to be readded to the URL
            for x in queries_list:
                if x.find("utm") != -1:
                    utm_detected = True
                    tracker_type = "UTM tracking"
                    #print(url)
                #elif x.find("s") != -1 and url.find("twitter") != -1:
                    #utm_detected = True
                    #tracker_type = "Twitter's weird tracking"
                else:
                    new_query.append(x)

            #replaces the original queries with the clean queries
            parsed_url = parsed_url._replace(query= "&".join(new_query))

            #if a tracker was detected send a message with the tracking type and the unparsed url
            if utm_detected:
                await message.channel.send(f"The above link featured {tracker_type}.\nHere is a fixed URL:\n> <{parsed_url.geturl()}>")

            print(parsed_url.geturl())

#IMPORTANT: Put your key here for anything to work
client.run('KEY GOES HERE')